package com.lbmb.photodrawaimanager.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lbmb.photodrawaimanager.entity.dto.VideoEntity;
import com.lbmb.photodrawaimanager.entity.req.VideoReq;
import com.lbmb.photodrawaimanager.entity.resp.VideoUserResp;
import com.lbmb.photodrawaimanager.enums.ErrorCode;
import com.lbmb.photodrawaimanager.exception.BusinessException;
import com.lbmb.photodrawaimanager.service.VideoService;
import com.lbmb.photodrawaimanager.utils.OssUtils;
import com.lbmb.photodrawaimanager.utils.PageUtils;
import com.lbmb.photodrawaimanager.utils.Response;
import com.volcengine.model.request.GetImageComicResultRequest;
import com.volcengine.model.response.GetImageComicResultResponse;
import com.volcengine.service.imagex.IImageXService;
import com.volcengine.service.imagex.impl.ImageXServiceImpl;
import com.volcengine.service.visual.IVisualService;
import com.volcengine.service.visual.impl.VisualServiceImpl;
import com.volcengine.service.visual.model.request.VisualAIGufengRequest;
import com.volcengine.service.visual.model.request.VisualJPCartoonRequest;
import com.volcengine.service.visual.model.response.VisualAIGufengResponse;
import com.volcengine.service.visual.model.response.VisualJPCartoonResponse;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Base64;
import java.util.UUID;

/**
 * @author hanWang
 * @Title:
 * @Package
 * @Description:
 * @date 2023/8/211:54 下午
 */
@RestController
@RequestMapping("/api/v1/video")
//@CrossOrigin
public class VideoController
{

    @Autowired
    VideoService videoService;

    @PostMapping("/uploadOneFile")
    public Response<Boolean> uploadFile(@RequestPart(value = "file", required = true)MultipartFile file,@RequestPart(value = "imgFile", required = true)MultipartFile imgFile, @RequestPart(value = "req") @Validated VideoReq req) {
        //返回上传oss的url
        return Response.ok(videoService.uploadVideo(file,imgFile,req));
    }

    @PostMapping("query_all_video")
    public Response<?> queryAllVideo(@RequestBody VideoReq req) {
        //返回上传oss的url  throw new BusinessException(ErrorCode.GLOBAL_EXCEPTION);
        //
        return Response.ok(videoService.queryAllVideo(req));
    }

    @GetMapping("query_video_by_id")
    public Response<?> queryVideoById(@RequestParam("id") Long id) {
        //返回上传oss的url
        return Response.ok(videoService.queryVideoById(id));
    }

public static void main(String[] args) {
    IVisualService visualService = VisualServiceImpl.getInstance();

    // call below method if you dont set ak and sk in ～/.vcloud/config
    visualService.setAccessKey("AKLTOTI1OWRmNzg3YTY3NDZmYzhmNWUyODk2NmNmNWViZmU");
    visualService.setSecretKey("TldNMk5HSmhNRE0xT0RObU5ESXdNR0UyTVdRME16bG1PV0k0T1RReU5Eaw==");

    VisualJPCartoonRequest req = new VisualJPCartoonRequest();
    req.setImageBase64(getBase64("https://lbmb-center.oss-cn-shanghai.aliyuncs.com/2023/08/057d74924f3f9549b791890256502ed44f1.jpg"));
    req.setCartoonType("jpcartoon");
    req.setDoRisk(true);
    // req.setCartoonType("jpcartoon_head"); // jpcartoon_head | jpcartoon | hkcartoon
    // req.setRotation(1);

    try {
        VisualJPCartoonResponse response = visualService.jpCartoon(req);
        String image = response.getData().getImage();
        generateImage(image,"/Users/wanghan/Desktop/huoshan_Img/");
        System.out.println(JSON.toJSONString(response));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

    public static String generateImage(String base64, String path) {
        // 解密
        try {
            // 图片分类路径+图片名+图片后缀
            String imgClassPath = path.concat(UUID.randomUUID().toString()).concat(".jpg");
            // 去掉base64前缀 data:image/jpeg;base64,
            base64 = base64.substring(base64.indexOf(",", 1) + 1);
            // 解密，解密的结果是一个byte数组
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] imgbytes = decoder.decode(base64);
            for (int i = 0; i < imgbytes.length; ++i) {
                if (imgbytes[i] < 0) {
                    imgbytes[i] += 256;
                }
            }

            // 保存图片
            OutputStream out = new FileOutputStream(imgClassPath);
            out.write(imgbytes);
            out.flush();
            out.close();
            // 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
            return imgClassPath;
        } catch (IOException e) {
            return null;
        }
    }



    private static String getBase64(String baseurl) {
        InputStream in = null;
        final ByteArrayOutputStream data = new ByteArrayOutputStream();
        //读取图片字节数组
        try {
            URL url = new URL(baseurl);
            final byte[] by = new byte[1024];
            // 创建链接获取图片
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            in = conn.getInputStream();
            int len = -1;
            while ((len = in.read(by)) != -1) {
                data.write(by, 0, len);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        //返回Base64编码过的字节数组字符串
        String encode = encoder.encode(data.toByteArray());
        encode = encode.replaceAll("[\\s*\t\n\r]", "");
        return encode;
    }



}
